// 项目权重API - 使用封装层隐藏真实地址
import { api } from '../utils/apiWrapper.js'

// 获取项目权重列表
export async function getProjectPhaseWeightList(params) {
  try {
   // params={page:1,pageSize:1000}
    const result = await api.get('/api/data/project_phase_weight',params)
    return result
  } catch (error) {
    console.error('获取项目权重列表失败:', error)
    throw error
  }
}

// 根据项目ID获取权重列表
export async function getProjectPhaseWeightListByProjectId(projectId, page = 1, pageSize = 1000) {
  try {
    console.log('获取项目权重，项目ID:', projectId)
    const params={page:1,pageSize:1000,where:{project_id:projectId}}
    const result = await getProjectPhaseWeightList(params)
    console.log('API返回的原始数据:', result)
    
    // 处理不同的数据结构
    let records = []
    if (result.records && Array.isArray(result.records)) {
      records = result.records
    } else if (result.data && Array.isArray(result.data)) {
      records = result.data
    } else if (Array.isArray(result)) {
      records = result
    } else if (result.records && Array.isArray(result.records)) {
      records = result.records
    } else {
      console.error('API返回数据格式不正确:', result)
      return []
    }
    
    // 过滤当前项目的数据并按阶段编码排序
    const data = records.filter(item => item.project_id === projectId).sort((a, b) => {
      const getCodeNumber = code => parseFloat(code.replace('PL', ''));
      return getCodeNumber(a.phase_code) - getCodeNumber(b.phase_code);
    });
    
    console.log('处理后的权重数据:', data)
    return data;
  } catch (error) {
    console.error('根据项目ID获取权重列表失败:', error)
    throw error
  }
}

// 创建项目权重
export async function createProjectPhaseWeight(data) {
  try {
    return await api.post('/api/data/project_phase_weight',data)
  } catch (error) {
    console.error('创建项目权重失败:', error)
    throw error
  }
}

// 更新项目权重
export async function updateProjectPhaseWeight(id, data) {
  try {
    return await api.put(`/api/data/project_phase_weight/${id}`,data)
  } catch (error) {
    console.error('更新项目权重失败:', error)
    throw error
  }
}

// 删除项目权重
export async function deleteProjectPhaseWeight(id) {
  try {
    return await api.delete(`/api/data/project_phase_weight/${id}`)
  } catch (error) {
    console.error('删除项目权重失败:', error)
    throw error
  }
} 